package com.kun.springbootorder.task;

import cn.hutool.json.JSONUtil;
import com.kun.springbootorder.entity.Order;
import com.kun.springbootorder.entity.OrderMessage;
import com.kun.springbootorder.service.impl.OrderMessageServiceImpl;
import com.kun.springbootorder.service.impl.OrderServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;

import java.util.List;

@EnableScheduling
@Configuration
public class RabbitMqTask {
    @Autowired
    private OrderMessageServiceImpl orderMessageService;

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Scheduled(cron = "0/5 * * * * ?")
    public void RabbitMqTask() {
        System.out.println("开始检查消息发送失败的orderMessage");

        //1. 检查消息发送失败的orderMessage
        List<OrderMessage> orderMessages = orderMessageService.queryOrderMessagesByStatus(false);

        //2. 再次发送
        for (OrderMessage orderMessage : orderMessages) {
            Order order = orderService.queryOrderById(orderMessage.getOrderId());
            String jsonMessage = JSONUtil.toJsonStr(order);
            CorrelationData correlationData = new CorrelationData(String.valueOf(order.getOrderId()));
            rabbitTemplate.convertAndSend("order_fanout_exchange","",jsonMessage,correlationData);
        }
    }
}
